<template>
  <div class="init-container">
    <Modal
      class="userPrefModal"
      width="600"
      :value="userPrefModal"
      :title="$srv.getI18nByPath('others.userPrefConfig')"
      :mask-closable="false"
      draggable
      sticky
      :z-index="1"
      :ok-text="$srv.getI18nByValue('保存')"
      @on-ok="ok"
      :before-close="cancel"
      @on-cancel="hideModal"
    >
      <Form :model="formItem" :label-width="96">
        <Tabs
          :value="isByHome ? 'TemplateInfo' : 'global'"
          name="userPrefConfig"
        >
          <TabPane
            v-if="isByHome"
            :label="$srv.getI18nByValue('模板信息')"
            name="TemplateInfo"
            tab="userPrefConfig"
          >
            <Form
              ref="templateInfoForm"
              :model="templateInfo"
              :rules="ruleCustom"
              :label-width="96"
              label-colon
              class="templateInfoForm"
            >
              <FormItem :label="$srv.getI18nBySrv('title')" prop="title">
                <!-- <Input v-model="templateInfo.title" type="text" clearable /> -->
                <o-i18n-selector
                  :disabled="false"
                  v-model="templateInfo.title"
                  @on-blur="saveChanges"
                  :placeholder="$srv.getLangPathByValue('请输入模板名')"
                ></o-i18n-selector>
              </FormItem>
              <FormItem
                :label="$srv.getI18nBySrv('f_comment')"
                prop="f_comment"
              >
                <Input v-model="templateInfo.f_comment" type="text" clearable />
              </FormItem>
              <FormItem :label="$srv.getI18nBySrv('f_type')">
                <Select
                  v-model="templateInfo.f_type"
                  :disabled="!isAdministratorRole"
                >
                  <Option
                    v-for="(item, ind) in groupCode"
                    :key="ind"
                    :value="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </Form>
          </TabPane>
          <TabPane
            v-for="(tabInfo, tabName) in formItem"
            :key="tabName"
            :label="$srv.getI18nByPath(`others.${tabName}`)"
            :name="tabName"
            tab="userPrefConfig"
          >
            <!-- 大类的if语句：当用户喜好的分类之大类（即对应tabs页签）是global时-->
            <div v-if="tabName === 'global'" class="every_group_option">
              <FormItem
                v-for="(val, key) in tabInfo"
                :key="key"
                :label="$srv.getI18nByPath(`others.${key}`)"
              >
                <Select
                  v-if="key.indexOf('Family') !== -1"
                  v-model="formItem[tabName][key]"
                >
                  <Option
                    v-for="(item, ind) in fontFamilyData"
                    :key="ind"
                    :value="item"
                    >{{ item }}</Option
                  >
                </Select>
                <Select v-else v-model="formItem[tabName][key]">
                  <Option
                    v-for="(item, ind) in fontSizeData"
                    :key="ind"
                    :value="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </div>
            <!-- 大类的else语句：当用户喜好的分类之大类不是global时 -->
            <template v-else>
              <template v-for="(groupInfo, groupName) in tabInfo">
                <!-- if语句：当分组的键名是nav时，需要多循环一层 -->
                <template v-if="groupName === 'nav'">
                  <template v-for="(navInfo, navKey) in groupInfo">
                    <div :key="navKey">
                      <div class="title_line">
                        <Divider type="vertical" />
                        <span>{{
                          $srv.getI18nByPath(`others.${navKey}`)
                        }}</span>
                      </div>
                      <div class="every_group_option">
                        <FormItem
                          v-for="(val, key) in navInfo"
                          :key="key"
                          :label="$srv.getI18nByPath(`others.${key}`)"
                        >
                          <ColorPicker
                            v-model="formItem[tabName][groupName][navKey][key]"
                            alpha
                          />
                          <!-- <Select
                            v-model="formItem[tabName][groupName][navKey][key]"
                            v-if="
                              key.indexOf('bgc') !== -1 ||
                              key.indexOf('Bgc') !== -1
                            "
                          >
                            <template #prefix>
                              <Icon
                                type="ios-square"
                                :style="{
                                  color: formItem[tabName][groupName][navKey][
                                    key
                                  ]
                                    ? formItem[tabName][groupName][navKey][key]
                                    : 'transparent'
                                }"
                              />
                            </template>
                            <Option
                              v-for="(item, ind) in bgColorData"
                              :key="ind"
                              :value="item"
                              ><span
                                class="color_option"
                                :style="{ background: item }"
                              ></span
                              >{{ item }}</Option
                            >
                          </Select>
                          <Select
                            v-model="formItem[tabName][groupName][navKey][key]"
                            v-else-if="
                              key.indexOf('fontC') !== -1 ||
                              key.indexOf('FontC') !== -1
                            "
                          >
                            <template #prefix>
                              <Icon
                                type="ios-square"
                                :style="{
                                  color: formItem[tabName][groupName][navKey][
                                    key
                                  ]
                                    ? formItem[tabName][groupName][navKey][key]
                                    : 'transparent'
                                }"
                              />
                            </template>
                            <Option
                              v-for="(item, ind) in fontColorData"
                              :key="ind"
                              :value="item"
                              ><span
                                class="color_option"
                                :style="{ background: item }"
                              ></span
                              >{{ item }}</Option
                            >
                          </Select> -->
                        </FormItem>
                      </div>
                    </div>
                  </template>
                </template>
                <!-- else语句：当分组的键名不是nav时 -->
                <div v-else :key="groupName">
                  <div class="title_line">
                    <Divider type="vertical" />
                    <span>{{ $srv.getI18nByPath(`others.${groupName}`) }}</span>
                  </div>
                  <div class="every_group_option">
                    <FormItem
                      v-for="(val, key) in groupInfo"
                      :key="key"
                      :label="$srv.getI18nByPath(`others.${key}`)"
                    >
                      <ColorPicker
                        v-model="formItem[tabName][groupName][key]"
                        alpha
                      />
                      <!-- <Select
                        v-model="formItem[tabName][groupName][key]"
                        v-if="
                          key.indexOf('bgc') !== -1 || key.indexOf('Bgc') !== -1
                        "
                      >
                        <template #prefix>
                          <Icon
                            type="ios-square"
                            :style="{
                              color: formItem[tabName][groupName][key]
                                ? formItem[tabName][groupName][key]
                                : 'transparent'
                            }"
                          />
                        </template>
                        <Option
                          v-for="(item, ind) in bgColorData"
                          :key="ind"
                          :value="item"
                          ><span
                            class="color_option"
                            :style="{ background: item }"
                          ></span
                          >{{ item }}</Option
                        >
                      </Select>
                      <Select
                        v-model="formItem[tabName][groupName][key]"
                        v-else-if="
                          key.indexOf('fontC') !== -1 ||
                          key.indexOf('FontC') !== -1
                        "
                      >
                        <template #prefix>
                          <Icon
                            type="ios-square"
                            :style="{
                              color: formItem[tabName][groupName][key]
                                ? formItem[tabName][groupName][key]
                                : 'transparent'
                            }"
                          />
                        </template>
                        <Option
                          v-for="(item, ind) in fontColorData"
                          :key="ind"
                          :value="item"
                          ><span
                            class="color_option"
                            :style="{ background: item }"
                          ></span
                          >{{ item }}</Option
                        >
                      </Select> -->
                    </FormItem>
                  </div>
                </div>
              </template>
            </template>
          </TabPane>
        </Tabs>
      </Form>
    </Modal>
  </div>
  <!-- 一个组件要调用多个相同组件时,传入compBoxInfo对象，让子组件注册在一个组件箱内-->
  <!--例：<xxx :compBoxInfo="GT_compBoxInfo" -->
  <!-- 一个组件要调用多个相同组件时,组件箱内引用实例冲突。不需传入compBoxInfo由组件内部产生实例，只需接收compBoxInfo对象-->
  <!--例：<xxx  @compBoxInfo="set???CompBoxInfo"-->
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  fontFamilyData,
  groupCode
} from './config';

@T_srv.comp
export default class userPref extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({ default: false }) userPrefModal: boolean;

  @T_srv.prop() config!: any;

  @T_srv.prop({ default: false }) isByHome: any;

  @T_srv.ref('templateInfoForm') readonly templateInfoForm!: any;

  @T_srv.watch('config')
  changeConfigData(val) {
    let data;
    if (val.f_type === 0) {
      data = Tsrv.TPP.getDefConfig();
    } else {
      data = Tsrv.TPP.getPersonalConfig();
    }

    const config = data.filter(item => item.id === val.id)[0];
    const obj = {
      title: config.title,
      f_type: config.f_type,
      f_comment: config.f_comment,
      id: config.id,
      _sys_user_id: config._sys_user_id
    };
    this.userPreferences.templateInfo = obj;
    let config1;
    if (Tsrv.utils.isJSONString(config.f_data)) {
      config1 = JSON.parse(config.f_data);
    } else {
      config1 = config.f_data;
    }
    // const content = {
    //   view: {
    //     global: config1.view.global,
    //     home: config1.view.home,
    //     components: config1.view.components
    //   },
    //   layout: {

    //   }
    // }
    this.userPreferences.f_data = config1;

    this.formItem = this.userPreferences.f_data;
    this.oldFormData = Tsrv.utils.clone(this.userPreferences, true);

    this.templateInfo = this.userPreferences.templateInfo;
  }

  // get getData() {
  //   const datas = [];
  //   this.config.data.forEach(el => {
  //     datas.push({
  //       key: el.key,
  //       label: Tsrv.getI18nBySrv(el.label)
  //     });
  //   });
  //   return datas;
  // }

  /* 组件名 */
  // private name:string = '???'
  // private funName:string = ''
  // private G_compName : string = this.name
  /* 组件箱信息对象 */
  // private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  // private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  // private G_compID: string;
  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  //  public isMask: boolean = false;
  private formItem = {
    global: {},
    home: {
      nav: {
        firstNav: {},
        secondNav: {}
      },
      top: {},
      main: {}
    },
    components: {
      tabs: {},
      collapse: {},
      basegrid: {},
      baseform: {},
      basepanel: {},
      treegrid: {},
      multiform: {},
      graph: {},
      dateNav: {},
      modal: {}
    }
  };

  private fontFamilyData: string[] = fontFamilyData();

  private groupCode: any = groupCode();

  private userPreferences: any = {};

  private oldFormData = {
    global: {},
    home: {
      nav: {
        firstNav: {},
        secondNav: {}
      },
      top: {},
      main: {}
    },
    components: {
      tabs: {},
      collapse: {},
      basegrid: {},
      baseform: {},
      basepanel: {},
      treegrid: {},
      multiform: {},
      graph: {},
      dateNav: {},
      modal: {}
    }
  };

  private closeCheck: boolean = false;

  // private isByHome: boolean = false;

  // form校验
  private ruleCustom: any = {
    title: [
      { required: true, validator: this.validateString, trigger: 'blur' }
    ],
    f_comment: [
      { required: true, validator: this.validateString, trigger: 'blur' }
    ]
  };

  private isAdministratorRole: boolean =
    Tsrv.store.getters.SysInfo.roleInfo[0].roleType === 1;

  private templateInfo = {
    title: '',
    f_type: 1,
    f_comment: ''
  };

  created() {
    // 如果父组件没有传参，那就产生一个
    // this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    // this.G_compID = this.GT_compBoxInfo.compID;
    //  this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    // this.GT_command.init(this, this.GT_compBoxInfo);
  }

  mounted() {
    /* 向父组件发送实例 */
    // this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    // this.emit('compBoxInfo',this.GT_compBoxInfo);
  }

  destroyed() {
    /* 注册组件销毁 */
    // this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    // if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
    //     this.GT_compBox.removeCompsWithCompID(this.G_compID);
    // } else {
    //     this.GT_compBox.removeCompsMergeName(this.G_compID, [`'${this.G_compName}'`]);
    // }
    // private init(){
    // this.funName= //当前配置中的功能名
    // }
    /* 设置组件整体遮罩 */
    // public setMask(p:boolean){this.isMask = p}
    // public getMask(p:boolean):boolean{return this.isMask;}
  }

  // 系统级校验
  private validateType(rule, value, callback) {
    if (
      rule?.field === 'f_type' &&
      value === 0 &&
      Tsrv.getUserNo() !== 'admin'
    ) {
      callback(new Error(Tsrv.getI18nByValue('无权限')));
    }
  }

  // 字符串类型输入框校验
  private validateString(rule, value, callback) {
    if (Tsrv.utils.noValue(value)) {
      callback(new Error(Tsrv.getI18nByValue('内容不能为空')));
    } else {
      if (rule?.field === 'title') {
        Tsrv.exists(
          Tsrv.globalVar.dbType.MYSQL,
          Tsrv.globalVar.tableName.SYS_USER_PREFE,
          { title: { $eq: value } }
        ).then(([ok, err]) => {
          if (ok) {
            callback(new Error(Tsrv.getI18nByValue('模板名重复')));
          } else {
            callback();
          }
        });
      }
    }
  }

  private ok() {
    if (!this.isByHome) {
      this.emitConfirm(this.formItem);
    } else {
      this.emitConfirm(this.userPreferences);
    }
    // this.emitConfirm(this.isByHome ? this.userPreferences : this.formItem);
  }

  private emitConfirm(currentData: Object) {
    this.isEditData(currentData, this.oldFormData);
    if (this.closeCheck) {
      this.$emit('confirm', currentData);
    } else {
      this.$Message.info('没有数据被更新');
      this.$emit('update:userPrefModal', false);
    }
  }

  private hideModal() {
    this.$emit('cancel');
  }

  private isEditData(newData: Object, oldData: Object) {
    const str1: string = Tsrv.utils.md5(JSON.stringify(newData));
    const str2: string = Tsrv.utils.md5(JSON.stringify(oldData));
    this.closeCheck = str1 !== str2;
  }

  private cloneFormItem(currentData) {
    currentData = Tsrv.utils.clone(this.oldFormData, true);
  }

  private cancel() {
    const that = this;
    return new Promise((resolve, reject) => {
      if (!this.isByHome) {
        this.isEditData(this.formItem, this.oldFormData);
      } else {
        this.isEditData(this.userPreferences, this.oldFormData);
      }
      if (this.closeCheck) {
        this.$Modal.confirm({
          title: Tsrv.getI18nByPath('others.isclosed') as string,
          content: Tsrv.getI18nByPath('others.isclosed') as string,
          onOk: () => {
            if (that.isByHome) {
              that.cloneFormItem(this.userPreferences);
            } else {
              that.cloneFormItem(this.formItem);
            }
            resolve(true);
          },
          onCancel: () => {
            reject(null);
          }
        });
      } else {
        resolve(true);
      }
    });
  }

  private saveChanges() {}
}
</script>
<style lang="scss" scoped>
.ivu-modal-wrap ::v-deep {
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal {
    top: 0;
  }
}
.ivu-tabs ::v-deep {
  height: 500px;
  .ivu-tabs-content {
    height: calc(100% - 50px);
    .ivu-tabs-tabpane {
      padding-right: 6px;
      height: 100%;
      overflow-y: auto;
      .ivu-divider {
        width: 2px;
        height: 13px;
        background: $default-hover-font-color;
      }
      .ivu-form-item {
        margin-bottom: 16px;
      }
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }
      /* 滚动条轨道样式 */
      &::-webkit-scrollbar-track {
        background: transparent;
      }
      /* 滚动条滑块样式 */
      &::-webkit-scrollbar-thumb {
        background: rgba(144, 147, 153, 0.2);
        border-radius: 4px;
      }
      /* 当滑块悬停或活动时的样式 */
      &::-webkit-scrollbar-thumb:hover {
        background: rgba(144, 147, 153, 0.4);
      }
    }
  }
}
.title_line {
  margin-bottom: 6px;
  height: 30px;
  line-height: 30px;
}
.title_line span {
  font-size: 14px;
}
.every_group_option {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ivu-form-item {
    margin-left: 12px;
    width: calc(50% - 12px);
  }
}
.color_option {
  display: inline-block;
  margin-right: 5px;
  width: 10px;
  height: 10px;
}
.templateInfoForm {
  padding-right: 40px;
}
</style>
